<template>
  <div class="app-container">
    <div class="form-box">
      <el-form ref="form" :model="form" label-width="120px" :rules="rules">
        <el-tabs type="border-card" class="form-tabs">
          <el-tab-pane :label="$t('common.edit_info')" class="form-tabs-tab-pane">
            <!-- 姓名/昵称 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.name_ext')" prop="name">
                  <el-input
                    v-model="form.name"
                    :placeholder="$t('common.name_ext_tips')"
                    :disabled="sys==1"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 用户名 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.username')" prop="username">
                  <el-input
                    v-model="form.username"
                    :placeholder="$t('common.username_tips')"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 密码 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.password')" prop="password">
                  <el-input
                    v-model="form.password"
                    :placeholder="$t('common.password_tips')"
                    type="password"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 确认密码 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.repassword')" prop="password_confirmation">
                  <el-input
                    v-model="form.password_confirmation"
                    :placeholder="$t('common.repassword_tips')"
                    type="password"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 头像 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('user.avatar_image')"
                  prop="avatar_image"
                >
                  <jsp-image-upload
                    :title="$t('user.avatar_image')"
                    :default-list="avatar_imageList"
                    :action="fileUploadConfig.imageAction"
                    :headers="fileUploadConfig.headers"
                    :size="Number(fileUploadConfig.allowImageSize)"
                    :accept="fileUploadConfig.allowImageTypeList"
                    @error="(error)=>{error!=null&&$message.error(error)}"
                    @change="handlePhotoImageUploadChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 介绍 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('user.description')"
                  prop="description"
                >
                  <el-input
                    v-model="form.description"
                    type="textarea"
                    :placeholder="$t('user.description_tips')"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 电话号码 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.phone_number')" prop="phone_number">
                  <el-input
                    v-model="form.phone_number"
                    :placeholder="$t('user.phone_number_tips')"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 电子邮箱 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.email')" prop="email">
                  <el-input
                    v-model="form.email"
                    :placeholder="$t('user.email_tips')"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 创建时间 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.created_at')">
                  {{ created_at }}
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 最近登录时间 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('user.last_login_time')">
                  {{ last_login_time }}
                </el-form-item>
              </el-col>
            </el-row>

          </el-tab-pane>
        </el-tabs>

        <el-row :gutter="20" type="flex" justify="center" class="btn-row">
          <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
            <el-form-item>
              <el-button type="primary" @click="onSubmit">{{
                $t('common.submit')
              }}</el-button>
              <el-button @click="onCancel">{{ $t('common.cancel') }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import JspImageUpload from '@/components/JspImageUpload'
import { getProfile, updateProfile } from '@/api/user'
import { mapGetters } from 'vuex'
import { loadingStart } from '@/utils/loading-service'

// export
export default {
  name: 'ProfileEdit',
  components: {
    JspImageUpload
  },
  data() {
    const usernameValidator = (rule, value, callback) => {
      const reg = /^[a-zA-Z]{1}[a-zA-Z0-9]+$/
      if ((!reg.test(value))) {
        callback(new Error(this.$t('common.username_format_tips')))
      } else {
        callback()
      }
    }
    const passwordConfirmationValidator = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error(this.$t('common.password_twice_error_tips')))
      } else {
        callback()
      }
    }

    const emailValidator = (rule, value, callback) => {
      const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (value && !reg.test(value)) {
        callback(new Error(this.$t('user.email_format_tips')))
      } else {
        callback()
      }
    }

    return {
      form: {
        name: '',
        username: '',
        password: '',
        password_confirmation: '',
        phone_number: '',
        email: '',
        avatar_image: 0,
        description: ''
      },
      avatar_imageList: [],
      // 表单输入校验 ，通过prop="name"属性进行控制
      rules: {
        name: [
          { required: true, message: this.$t('common.name_ext_tips'), trigger: 'blur' },
          { min: 2, max: 30, message: this.$t('user.name_length_tips'), trigger: 'blur' }
        ],
        username: [
          { required: true, message: this.$t('common.username_tips'), trigger: 'blur' },
          { min: 3, max: 50, message: this.$t('user.username_length_tips'), trigger: 'blur' },
          { validator: usernameValidator, trigger: 'blur' }
        ],
        password: [{ required: false, message: this.$t('common.password_tips'), trigger: 'blur' }],
        password_confirmation: [{ required: false, validator: passwordConfirmationValidator, trigger: 'blur' }],
        role_ids: [
          { required: true, message: this.$t('user.role_ids_tips'), trigger: 'blur' }
        ],
        phone_number: [
          { required: false, min: 0, max: 30, message: this.$t('user.phone_number_length_tips'), trigger: 'blur' }
        ],
        email: [
          { required: false, validator: emailValidator, trigger: 'blur' }
        ]
      },
      user_id: 0,
      sys: 0,
      created_at: '',
      last_login_time: ''

    }
  },
  computed: {
    ...mapGetters(['fileUploadConfig'])
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    async getDetail() {
      const loading = loadingStart()
      await getProfile().then((response) => {
        this.sys = response.data.sys
        this.user_id = response.data.id
        this.created_at = response.data.created_at
        this.last_login_time = response.data.last_login_time
        for (const key in response.data) {
          if (key in this.form) {
            this.form[key] = response.data[key]
          }
        }
      }).catch(() => {
        this.closeBack()
      })
      // 封面图
      this.avatar_imageList = this.form.avatar_image
      this.form.avatar_image = this.form.avatar_image.map((item) => {
        return item.id
      }).join(',')

      loading.close()
    },
    onSubmit() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          this.submitLoading = true
          await updateProfile(this.user_id, this.form).then((response) => {
            this.$message.success(response.message)
          }).catch(() => {})
          this.submitLoading = false
        } else {
          this.$message.error(this.$t('common.pleaseFillRequired'))
          return false
        }
      })
    },
    onCancel() {
      this.closeBack()
    },
    // 改变附件事件
    handlePhotoImageUploadChange(result) {
      this.form.avatar_image = result.ids
    }
  }
}
</script>

<style scoped lang="scss">
</style>
